'''
Created on 2011-07-26
@author: XH
'''
from socket import *
from time import ctime,sleep
import os
HOST=''
PORT=21582
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpSerSock=socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

#COMMAND-START
CMDDIC = {
'f'  : 'iptables -L -n',
'ps' : 'ps aux',
'os' : 'service sshd status',
'dir': 'dir/a',
'ip' : 'ipconfig'}
#COMMAND-END

def run(cmd):
    '''Execute command'''
    if cmd in CMDDIC:
        textlist = os.popen(CMDDIC[cmd]).readlines()
        for line in textlist:
            tcpCliSock.send(line)
            print line,
    else:
        tcpCliSock.send('Usage:  \n')
        print "Usage: "
        for command,name in CMDDIC.items():
            tcpCliSock.send('\t%s\t:%s \n' %(command,name))
            print "\t%s\t:%s " %(command,name)

try:
    while True:
        print 'waiting for connection...'
        tcpCliSock,addr=tcpSerSock.accept()
        print '...connected from:',addr

        while True:
            data=tcpCliSock.recv(BUFSIZ)
            print "[%s ]#%s" %(addr[0],data)

            if not data:
                break
            else:
                run(data)
    tcpCliSock.close()


except KeyboardInterrupt:
    tcpSerSock.close()
